<template>
  <div class="space-y-6">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between">
      <div>
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">成分列表</h2>
        <p class="mt-1 text-sm text-gray-500">管理植物的化学成分信息</p>
      </div>
      <button 
        class="mt-4 md:mt-0 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-custom flex items-center"
        @click="openDialog()"
      >
        <i class="fa fa-plus mr-2"></i>
        <span>新增成分</span>
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl shadow-custom p-6">
      <div class="flex flex-col md:flex-row md:items-center gap-4">
        <div class="flex-1">
          <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400">
              <i class="fa fa-search"></i>
            </span>
            <input 
              v-model="searchQuery" 
              type="text" 
              class="pl-10 pr-4 py-2 w-full border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-custom" 
              placeholder="搜索成分名称..."
            >
          </div>
        </div>
        <div class="flex items-center gap-4">
          <el-select v-model="plantFilter" placeholder="选择植物" clearable>
            <el-option
              v-for="plant in plants"
              :key="plant.id"
              :label="plant.name"
              :value="plant.id"
            />
          </el-select>
          <el-select v-model="sortBy" placeholder="排序方式">
            <el-option label="名称升序" value="name-asc" />
            <el-option label="名称降序" value="name-desc" />
            <el-option label="含量升序" value="content-asc" />
            <el-option label="含量降序" value="content-desc" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 成分列表 -->
    <div class="bg-white rounded-xl shadow-custom">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成分名称</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分子式</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">含量</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属植物</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">更新时间</th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="component in filteredComponents" :key="component.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ component.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ component.formula }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ component.content }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ component.plantName }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(component.updateTime) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
                <button 
                  class="text-primary hover:text-primary/80 transition-custom"
                  @click="openDialog(component)"
                >
                  <i class="fa fa-edit"></i>
                </button>
                <button 
                  class="text-danger hover:text-danger/80 transition-custom"
                  @click="confirmDelete(component)"
                >
                  <i class="fa fa-trash"></i>
                </button>
              </td>
            </tr>
            <tr v-if="filteredComponents.length === 0">
              <td colspan="6" class="px-6 py-4 text-center text-gray-500">暂无数据</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="px-6 py-4 flex items-center justify-between border-t border-gray-200">
        <div class="text-sm text-gray-500">
          共 {{ totalComponents }} 条记录
        </div>
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :total="totalComponents"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="成分名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入成分名称" />
        </el-form-item>
        <el-form-item label="分子式" prop="formula">
          <el-input v-model="form.formula" placeholder="请输入分子式" />
        </el-form-item>
        <el-form-item label="含量" prop="content">
          <el-input v-model="form.content" placeholder="请输入含量">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属植物" prop="plantId">
          <el-select v-model="form.plantId" placeholder="请选择植物">
            <el-option
              v-for="plant in plants"
              :key="plant.id"
              :label="plant.name"
              :value="plant.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="400px"
    >
      <p>确定要删除成分"{{ deleteComponent?.name }}"吗？此操作不可恢复。</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleDelete" :loading="deleting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ComponentList',
  data() {
    return {
      // 搜索和筛选
      searchQuery: '',
      plantFilter: '',
      sortBy: 'name-asc',
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      
      // 表单对话框
      dialogVisible: false,
      submitting: false,
      form: {
        id: null,
        name: '',
        formula: '',
        content: '',
        plantId: ''
      },

      // 删除对话框
      deleteDialogVisible: false,
      deleting: false,
      deleteComponent: null,

      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入成分名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        formula: [
          { required: true, message: '请输入分子式', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入含量', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的含量格式', trigger: 'blur' }
        ],
        plantId: [
          { required: true, message: '请选择所属植物', trigger: 'change' }
        ]
      },

      // 模拟数据
      components: [
        {
          id: 1,
          name: '银杏内酯A',
          formula: 'C20H24O9',
          content: '0.3-0.5',
          plantId: 1,
          plantName: '银杏',
          updateTime: '2024-03-15'
        },
        {
          id: 2,
          name: '银杏内酯B',
          formula: 'C20H24O10',
          content: '0.2-0.4',
          plantId: 1,
          plantName: '银杏',
          updateTime: '2024-03-15'
        },
        {
          id: 3,
          name: '人参皂苷Rb1',
          formula: 'C54H92O23',
          content: '0.8-1.2',
          plantId: 2,
          plantName: '人参',
          updateTime: '2024-03-14'
        }
      ],
      plants: [
        { id: 1, name: '银杏' },
        { id: 2, name: '人参' },
        { id: 3, name: '当归' }
      ]
    }
  },
  computed: {
    dialogTitle() {
      return this.form.id ? '编辑成分' : '新增成分'
    },
    filteredAndSortedComponents() {
      let result = [...this.components]

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item => 
          item.name.toLowerCase().includes(query) ||
          item.formula.toLowerCase().includes(query)
        )
      }

      // 植物过滤
      if (this.plantFilter) {
        result = result.filter(item => item.plantId === this.plantFilter)
      }

      // 排序
      switch (this.sortBy) {
        case 'name-asc':
          result.sort((a, b) => a.name.localeCompare(b.name))
          break
        case 'name-desc':
          result.sort((a, b) => b.name.localeCompare(a.name))
          break
        case 'content-asc':
          result.sort((a, b) => parseFloat(a.content) - parseFloat(b.content))
          break
        case 'content-desc':
          result.sort((a, b) => parseFloat(b.content) - parseFloat(a.content))
          break
      }

      return result
    },
    totalComponents() {
      return this.filteredAndSortedComponents.length
    },
    filteredComponents() {
      // 分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredAndSortedComponents.slice(start, end)
    }
  },
  methods: {
    formatDate(date) {
      return new Date(date).toLocaleDateString()
    },
    handlePageChange(page) {
      this.currentPage = page
    },
    openDialog(component = null) {
      if (component) {
        this.form = { ...component }
      } else {
        this.resetForm()
      }
      this.dialogVisible = true
    },
    resetForm() {
      this.form = {
        id: null,
        name: '',
        formula: '',
        content: '',
        plantId: ''
      }
      this.$refs.form?.resetFields()
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        this.submitting = true

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        if (this.form.id) {
          // 更新现有成分
          const index = this.components.findIndex(item => item.id === this.form.id)
          if (index !== -1) {
            const plant = this.plants.find(p => p.id === this.form.plantId)
            this.components[index] = {
              ...this.form,
              plantName: plant.name,
              updateTime: new Date().toISOString().split('T')[0]
            }
          }
        } else {
          // 添加新成分
          const plant = this.plants.find(p => p.id === this.form.plantId)
          this.components.push({
            ...this.form,
            id: this.components.length + 1,
            plantName: plant.name,
            updateTime: new Date().toISOString().split('T')[0]
          })
        }

        this.$message.success(this.form.id ? '更新成功' : '添加成功')
        this.dialogVisible = false
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        this.submitting = false
      }
    },
    confirmDelete(component) {
      this.deleteComponent = component
      this.deleteDialogVisible = true
    },
    async handleDelete() {
      if (!this.deleteComponent) return

      try {
        this.deleting = true
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        const index = this.components.findIndex(item => item.id === this.deleteComponent.id)
        if (index !== -1) {
          this.components.splice(index, 1)
        }

        this.$message.success('删除成功')
        this.deleteDialogVisible = false
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败')
      } finally {
        this.deleting = false
        this.deleteComponent = null
      }
    }
  }
}
</script>

<style scoped>
.transition-custom {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.shadow-custom {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
</style> 